<template>
  <div class="user-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input
            style="width: 210px"
            v-model="searchForm.nickname"
            placeholder="请输入用户昵称"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="角色名" prop="roleId">
          <el-select
            style="width: 210px"
            v-model="searchForm.roleId"
            placeholder="请选择角色"
          >
            <el-option
              v-for="option in roleList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="user-page-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增用户
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="userName" label="用户名" width="120">
            <template #default="scope">
              <div
                v-if="!scope.row.userName || scope.row.userName == 'NULL'"
              ></div>
              <div v-else>{{ scope.row.userName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称" width="150" />
          <el-table-column prop="phonenumber" label="手机号" width="120" />
          <el-table-column prop="roleName" label="角色名" min-width="180">
            <template #default="scope">
              <div class="tag-field">
                <el-tag v-for="item in scope.row.roleList" :key="item.id">{{
                  item.name
                }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="170" />
          <el-table-column prop="updateTime" label="更新时间" width="170" />
          <el-table-column label="操作" fixed="right" min-width="220px">
            <template #default="scope">
              <!-- v-if="userPermission.editUserPerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <!-- v-if="userPermission.removeUserPerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-if="addDialogVisible"
      v-model="addDialogVisible"
      :title="addEditForm.title"
      width="550px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditRef"
          :label-width="80"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              placeholder="请输入用户名"
              v-model="addEditForm.userName"
              autocomplete="off"
              :disabled="addEditForm.disabled || addEditForm.id"
            />
          </el-form-item>
          <el-form-item v-if="!addEditForm.id" label="密码" prop="password">
            <el-input
              placeholder="请输入密码"
              v-model="addEditForm.password"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
          <el-form-item label="角色" prop="roleIdList">
            <el-select
              v-model="addEditForm.roleIdList"
              placeholder="请选择角色"
              style="width: 100%"
              multiple
              :disabled="addEditForm.disabled"
            >
              <el-option
                v-for="option in roleList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input
              placeholder="请输入昵称"
              v-model="addEditForm.nickName"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input
              placeholder="请输入手机号"
              v-model="addEditForm.phonenumber"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!addEditForm.disabled">
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startAddRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-if="removeDialogVisible"
      v-model="removeDialogVisible"
      title="删除用户"
      width="400px"
    >
      <span>确定要删除当前用户？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemoveRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getUserPagination,
  removeUser,
  updateUser,
  addUser,
  getAllRoleList,
} from '@/api/ums-user.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useUserPermission } from '@/utils/permission.utils'
const userPermission = useUserPermission()
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  nickname: '',
  roleId: '',
})

const removeDialogVisible = ref(false)
const addDialogVisible = ref(false)
const addEditRef = ref<FormInstance>()
const addEditForm = reactive({
  id: null,
  password: '',
  nickName: '',
  phonenumber: '',
  userName: '',
  disabled: false,
  title: '',
  roleIdList: [],
})
const addEditRules = reactive({
  userName: [
    { required: true, message: '请输入11位手机号作为用户名', trigger: 'blur' },
    {
      min: 11,
      max: 11,
      message: '请输入11位手机号作为用户名',
      trigger: 'blur',
    },
  ],
  roleId: [{ required: true, message: '请选择用户角色', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入6~30位密码', trigger: 'blur' },
    { min: 6, max: 30, message: '请输入6~30位密码', trigger: 'blur' },
  ],
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  phonenumber: [
    { required: true, message: '请输入11位手机号码', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
  ],
})

/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 重置搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const showAddEditDialog = (item: any, type: number) => {
  //新增用户
  if (item.target) {
    addEditForm.id = null
    addEditForm.userName = ''
    addEditForm.password = ''
    addEditForm.nickName = ''
    addEditForm.phonenumber = ''
    addEditForm.roleIdList = []
    addEditForm.title = '新增用户'
    addDialogVisible.value = true
    return
  }

  addEditForm.id = item.id
  addEditForm.userName = item.userName
  addEditForm.password = item.password
  addEditForm.nickName = item.nickName
  addEditForm.phonenumber = item.phonenumber
  addEditForm.roleIdList = item.roleIdList
  //编辑
  addEditForm.title = '编辑用户'
  addEditForm.disabled = false
  addDialogVisible.value = true
}

const tableLoading = ref(false)
const tableData = ref([])

const curSelectRow = ref('')
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true
  curSelectRow.value = item
  console.log('item: ', item)
}

const startRemoveRole = () => {
  let id = curSelectRow.value?.id
  removeUser([id])
    .then((res) => {
      console.log('success~~~~~')
      removeDialogVisible.value = false
      ElMessage({
        message: '用户删除成功',
        type: 'success',
      })
      getDataList()
    })
    .catch((err) => {
      ElMessage({
        message: err.msg || err,
        type: 'error',
      })
    })
}

const startAddRole = () => {
  let formData = {
    userName: addEditForm.userName,
    password: addEditForm.password,
    nickName: addEditForm.nickName,
    phonenumber: addEditForm.phonenumber,
    roleIdList: addEditForm.roleIdList,
  }

  if (!addEditRef.value) return
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (addEditForm.id) {
        updateUser({
          ...formData,
          id: addEditForm.id,
        })
          .then((res) => {
            addDialogVisible.value = false
            ElMessage({
              message: '用户修改成功',
              type: 'success',
            })
            getDataList()
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: 'error',
            })
          })
        return
      }

      addUser(formData)
        .then((res) => {
          addDialogVisible.value = false
          ElMessage({
            message: '用户新增成功',
            type: 'success',
          })
          getDataList()
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}

const handleSizeChange = (value: number) => {
  console.log('handleSizeChange...', value)
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  console.log('handleCurrentChange...', value)
  formData.pageIndex = value
  getDataList()
}

interface SearchCondiction {
  roleId?: string
  nickname?: string
}

const getDataList = () => {
  let searchCondition: SearchCondiction = {}
  if (searchForm.value.roleId) {
    searchCondition.roleId = searchForm.value.roleId
  }
  if (searchForm.value.nickname) {
    searchCondition.nickname = searchForm.value.nickname
  }

  tableLoading.value = true
  getUserPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)
      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const roleList = ref([])
const startGetAllRoleList = () => {
  getAllRoleList({}).then(function (res: any) {
    console.log('startGetAllRoleList: ', res)
    roleList.value = res
  })
}

onMounted(() => {
  getDataList()
  startGetAllRoleList()
})
</script>
<style lang="scss" scoped>
.user-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.user-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
